<template>
  <div class="real-time-orders">
    <div class="orders-header">
      <h3 class="orders-title">实时订单流</h3>
      <div class="orders-stats">
        <span class="online-indicator">
          <span class="pulse-dot"></span>
          实时
        </span>
        <div class="order-count">
          <span class="count-label">今日订单</span>
          <span class="count-value">{{ totalOrdersToday }}</span>
        </div>
      </div>
    </div>
    
    <div class="orders-content">
      <div class="orders-scroll">
        <div 
          v-for="(order, index) in currentOrders" 
          :key="order.id"
          class="order-item"
          :class="{ 'new-order': order.isNew }"
          :style="{ animationDelay: index * 50 + 'ms' }"
        >
          <div class="order-avatar">
            <div class="avatar-bg" :style="{ background: order.avatarColor }">
              {{ order.user.charAt(0) }}
            </div>
            <div v-if="order.isNew" class="new-badge">新</div>
          </div>
          <div class="order-info">
            <div class="order-user">{{ order.user }}</div>
            <div class="order-product">购买了 {{ order.product }}</div>
            <div class="order-details">
              <span class="order-time">{{ order.timeAgo }}</span>
              <span class="order-status" :class="order.status">{{ getStatusText(order.status) }}</span>
            </div>
          </div>
          <div class="order-amount">
            <div class="amount-value">¥{{ order.amount }}</div>
            <div class="order-location">{{ order.location }}</div>
          </div>
        </div>
        <!-- 占位符补齐 -->
        <div 
          v-for="n in (itemsPerPage - currentOrders.length)" 
          :key="'placeholder-' + n" 
          class="order-item order-placeholder"
          style="visibility: hidden;"
        ></div>
      </div>
      <div class="pagination-dots">
        <span v-for="idx in totalPages" :key="idx" class="dot" :class="{ active: idx - 1 === currentPage }"></span>
      </div>
    </div>
    
    <!-- 实时统计 -->
    <div class="orders-footer">
      <div class="stat-item">
        <span class="stat-label">活跃用户</span>
        <span class="stat-value">{{ activeUsers }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">每分钟订单</span>
        <span class="stat-value">{{ ordersPerMinute }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 直接初始化数据
const displayOrders = ref([
  {
    id: '1001',
    user: '张小明',
    product: 'iPhone 15 Pro Max',
    amount: '6,999',
    location: '北京',
    timeAgo: '刚刚',
    avatarColor: '#ff6b6b',
    timestamp: Date.now(),
    isNew: true,
    status: 'paid'
  },
  {
    id: '1002',
    user: '李小红',
    product: '华为Mate 60 Pro',
    amount: '5,499',
    location: '上海',
    timeAgo: '1分钟前',
    avatarColor: '#4ecdc4',
    timestamp: Date.now() - 60000,
    isNew: false,
    status: 'processing'
  },
  {
    id: '1003',
    user: '王大强',
    product: 'MacBook Pro M3',
    amount: '12,999',
    location: '深圳',
    timeAgo: '2分钟前',
    avatarColor: '#45b7d1',
    timestamp: Date.now() - 120000,
    isNew: false,
    status: 'shipped'
  },
  {
    id: '1004',
    user: '赵小芳',
    product: 'iPad Air 5',
    amount: '4,299',
    location: '广州',
    timeAgo: '3分钟前',
    avatarColor: '#96ceb4',
    timestamp: Date.now() - 180000,
    isNew: false,
    status: 'paid'
  },
  {
    id: '1005',
    user: '钱志豪',
    product: 'AirPods Pro 2',
    amount: '1,999',
    location: '杭州',
    timeAgo: '4分钟前',
    avatarColor: '#feca57',
    timestamp: Date.now() - 240000,
    isNew: false,
    status: 'pending'
  },
  {
    id: '1006',
    user: '孙美丽',
    product: '华为手表GT4',
    amount: '1,688',
    location: '成都',
    timeAgo: '5分钟前',
    avatarColor: '#ff9ff3',
    timestamp: Date.now() - 300000,
    isNew: false,
    status: 'processing'
  }
])

let orderTimer = null
let statsTimer = null

// 实时统计数据
const totalOrdersToday = ref(15847)
const activeUsers = ref(1258)
const ordersPerMinute = ref(23)

// 扩展的模拟数据
const userNames = [
  '张小明', '李小红', '王大强', '赵小芳', '钱志豪', '孙美丽', '周杰伦', '吴亦凡', 
  '郑爽', '陈晓明', '刘德华', '马云', '王思聪', '李彦宏', '马化腾', '雷军', 
  '丁磊', '张朝阳', '程维', '王兴', '张一鸣', '黄峥', '沈南鹏', '徐小平'
]

const products = [
  'iPhone 15 Pro Max', '华为Mate 60 Pro', '小米14 Ultra', 'MacBook Pro M3', 'iPad Air 5',
  '华为手表GT4', '小米Buds 4', 'AirPods Pro 2', '戴森V12吸尘器', '海尔洗衣机XQG80',
  'Tesla Model Y', 'BMW X5', '耐克Air Jordan', '阿迪达斯Yeezy', 'LV手提包',
  '索尼PS5', 'Xbox Series X', 'Switch OLED', '罗技G Pro', '雷蛇DeathAdder',
  '茅台酒', '五粮液', '剑南春', '泸州老窖', '郎酒'
]

const cities = [
  '北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '西安', '武汉', '南京',
  '天津', '苏州', '青岛', '大连', '宁波', '厦门', '福州', '济南', '长沙', '郑州'
]

const avatarColors = [
  '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', 
  '#54a0ff', '#5f27cd', '#48dbfb', '#0abde3', '#ff3838', '#ff9500'
]

const orderStatuses = ['pending', 'processing', 'paid', 'shipped']

// 生成实时订单
const generateRealtimeOrder = () => {
  const basePrice = Math.random() < 0.1 ? 50000 : Math.random() < 0.3 ? 10000 : 1000
  const amount = Math.floor(basePrice + Math.random() * basePrice * 2)
  
  return {
    id: Date.now() + Math.random(),
    user: userNames[Math.floor(Math.random() * userNames.length)],
    product: products[Math.floor(Math.random() * products.length)],
    amount: amount.toLocaleString(),
    location: cities[Math.floor(Math.random() * cities.length)],
    timeAgo: '刚刚',
    avatarColor: avatarColors[Math.floor(Math.random() * avatarColors.length)],
    timestamp: Date.now(),
    isNew: true,
    status: orderStatuses[Math.floor(Math.random() * orderStatuses.length)]
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    processing: '处理中', 
    paid: '已付款',
    shipped: '已发货'
  }
  return statusMap[status] || '处理中'
}

// 更新时间显示
const updateOrderTimeAgo = (order) => {
  const now = Date.now()
  const diff = now - order.timestamp
  if (diff < 60000) {
    order.timeAgo = '刚刚'
  } else if (diff < 3600000) {
    order.timeAgo = `${Math.floor(diff / 60000)}分钟前`
  } else {
    order.timeAgo = `${Math.floor(diff / 3600000)}小时前`
  }
}

// 更新所有订单的时间显示和新标记
const updateAllTimeAgo = () => {
  displayOrders.value.forEach(order => {
    updateOrderTimeAgo(order)
    // 5秒后移除新标记
    if (order.isNew && Date.now() - order.timestamp > 5000) {
      order.isNew = false
    }
  })
}

// 添加新订单
const addNewOrder = () => {
  const newOrder = generateRealtimeOrder()
  newOrder.timestamp = Date.now()
  updateOrderTimeAgo(newOrder)
  
  console.log('新订单:', newOrder.user, '购买了', newOrder.product, '¥' + newOrder.amount)
  
  displayOrders.value.unshift(newOrder)
  
  // 最多保留25条记录
  if (displayOrders.value.length > 25) {
    displayOrders.value.splice(25)
  }
  
  // 更新统计数据
  totalOrdersToday.value += 1
  
  console.log('当前订单数量:', displayOrders.value.length)
}

// 更新实时统计
const updateStats = () => {
  // 模拟活跃用户数波动
  const userChange = Math.floor((Math.random() - 0.5) * 50)
  activeUsers.value = Math.max(1000, Math.min(2000, activeUsers.value + userChange))
  
  // 模拟每分钟订单数波动
  const orderChange = Math.floor((Math.random() - 0.5) * 10)
  ordersPerMinute.value = Math.max(15, Math.min(35, ordersPerMinute.value + orderChange))
}

// 分页逻辑修正：currentOrders基于displayOrders分页
const itemsPerPage = 8
const currentPage = ref(0)
const totalPages = computed(() => Math.ceil(displayOrders.value.length / itemsPerPage))
const currentOrders = computed(() => {
  const start = currentPage.value * itemsPerPage
  return displayOrders.value.slice(start, start + itemsPerPage)
})
let pageTimer = null

onMounted(() => {
  console.log('RealTimeOrders 组件已挂载')
  console.log('初始订单数量:', displayOrders.value.length)
  
  // 3秒后开始随机添加订单
  setTimeout(() => {
    const startOrderTimer = () => {
      const randomDelay = Math.random() * 3000 + 2000 // 2-5秒
      setTimeout(() => {
        addNewOrder()
        updateAllTimeAgo()
        startOrderTimer()
      }, randomDelay)
    }
    
    console.log('启动订单生成器')
    startOrderTimer()
  }, 3000)
  
  // 每5秒更新统计数据
  statsTimer = setInterval(() => {
    updateStats()
  }, 5000)
  
  // 每秒更新时间显示
  orderTimer = setInterval(() => {
    updateAllTimeAgo()
  }, 1000)

  pageTimer = setInterval(() => {
    currentPage.value = (currentPage.value + 1) % totalPages.value
  }, 5000)
})

onUnmounted(() => {
  console.log('RealTimeOrders 组件卸载')
  if (orderTimer) {
    clearInterval(orderTimer)
  }
  if (statsTimer) {
    clearInterval(statsTimer)
  }
  if (pageTimer) clearInterval(pageTimer)
})
</script>

<style scoped>
.real-time-orders {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: rgba(15, 52, 96, 0.3);
  border-radius: 12px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(10px);
  padding: 16px;
  overflow: hidden;
  min-height: 626px;
  max-height: 480px;
}

.orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 4px;
  border-bottom: 1px solid rgba(0, 240, 255, 0.1);
  min-height: unset;
}

.orders-title {
  color: #00f0ff;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.orders-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.online-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #00ff9d;
  font-size: 12px;
  font-weight: 500;
}

.pulse-dot {
  width: 8px;
  height: 8px;
  background: #00ff9d;
  border-radius: 50%;
  animation: pulse-animation 2s infinite;
}

@keyframes pulse-animation {
  0% {
    box-shadow: 0 0 0 0 rgba(0, 255, 157, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(0, 255, 157, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(0, 255, 157, 0);
  }
}

.orders-content {
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 250px;
}

.orders-scroll {
  height: 100%;
  overflow-y: auto;
  padding-right: 8px;
  min-height: 250px;
}

.orders-scroll::-webkit-scrollbar {
  width: 3px;
}

.orders-scroll::-webkit-scrollbar-track {
  background: rgba(0, 240, 255, 0.05);
  border-radius: 2px;
}

.orders-scroll::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, rgba(0, 240, 255, 0.3), rgba(0, 255, 157, 0.3));
  border-radius: 2px;
}

.orders-scroll::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, rgba(0, 240, 255, 0.5), rgba(0, 255, 157, 0.5));
}

.order-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  margin-bottom: 6px;
  background: rgba(0, 240, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(0, 240, 255, 0.1);
  transition: all 0.3s ease;
  animation: slideInFromRight 0.5s ease-out;
}

.order-item:hover {
  background: rgba(0, 240, 255, 0.1);
  transform: translateX(-2px);
  border-color: rgba(0, 240, 255, 0.3);
}

@keyframes slideInFromRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.order-avatar {
  flex-shrink: 0;
}

.avatar-bg {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  position: relative;
  transition: all 0.3s ease;
}

.avatar-bg::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(45deg, transparent, rgba(0, 240, 255, 0.3), transparent);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.order-item:hover .avatar-bg::before {
  opacity: 1;
  animation: avatarGlow 2s ease-in-out infinite;
}

@keyframes avatarGlow {
  0%, 100% {
    transform: scale(1) rotate(0deg);
  }
  50% {
    transform: scale(1.1) rotate(180deg);
  }
}

.order-info {
  flex: 1;
  min-width: 0;
}

.order-user {
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 2px;
}

.order-product {
  color: rgba(255, 255, 255, 0.8);
  font-size: 10px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-details {
  display: flex;
  align-items: center;
  gap: 4px;
}

.order-time {
  color: rgba(255, 255, 255, 0.5);
  font-size: 9px;
}

.order-status {
  color: #00ff9d;
  font-size: 9px;
  font-weight: 600;
}

.order-amount {
  text-align: right;
  flex-shrink: 0;
}

.amount-value {
  color: #00ff9d;
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 2px;
}

.order-location {
  color: rgba(0, 240, 255, 0.8);
  font-size: 9px;
}

.new-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background: #00ff9d;
  color: #151515;
  font-size: 8px;
  font-weight: 600;
  padding: 2px 4px;
  border-radius: 4px;
  animation: badgeBounce 1s ease-out;
}

@keyframes badgeBounce {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.orders-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  margin-top: 12px;
  border-top: 1px solid rgba(0, 240, 255, 0.1);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  color: rgba(255, 255, 255, 0.5);
  font-size: 10px;
  margin-bottom: 4px;
}

.stat-value {
  color: #00ff9d;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.stat-value:hover {
  transform: scale(1.1);
}

.order-status.paid {
  color: #00ff9d;
}

.order-status.processing {
  color: #feca57;
}

.order-status.pending {
  color: #ff6b6b;
}

.order-status.shipped {
  color: #00f0ff;
}

.order-count {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-left: 16px;
  font-size: 14px;
}

.count-label {
  color: rgba(255, 255, 255, 0.6);
  font-size: 10px;
  margin-bottom: 2px;
}

.count-value {
  color: #00f0ff;
  font-size: 16px;
  font-weight: 700;
  animation: counterPulse 3s ease-in-out infinite;
}

@keyframes counterPulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

/* 新订单特殊效果 */
.new-order {
  background: linear-gradient(90deg, rgba(0, 255, 157, 0.15), rgba(0, 240, 255, 0.05));
  border-color: rgba(0, 255, 157, 0.3);
  animation: newOrderPulse 2s ease-out;
}

@keyframes newOrderPulse {
  0% {
    transform: scale(1.02);
    box-shadow: 0 0 20px rgba(0, 255, 157, 0.4);
  }
  50% {
    transform: scale(1.01);
    box-shadow: 0 0 15px rgba(0, 255, 157, 0.2);
  }
  100% {
    transform: scale(1);
    box-shadow: none;
  }
}

.pagination-dots {
  display: flex;
  justify-content: center;
  gap: 6px;
  margin-top: 8px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #00f0ff44;
  transition: background 0.3s;
}

.dot.active {
  background: #00f0ff;
}

.order-item.order-placeholder {
  background: none !important;
  border: none !important;
  box-shadow: none !important;
  min-height: 0;
  padding: 0;
  margin: 0;
}
</style> 